# coding=utf-8
import random
import time
import os
from flask import Flask, url_for, abort, redirect, request, make_response, render_template, Blueprint, json, jsonify, \
    session

from Assistance.database import *
from flask_sqlalchemy import SQLAlchemy
import pymysql
import json
import datetime

from Assistance.result import Result
from Assistance.tools import isUsernameLegal
from gevent import pywsgi

pymysql.install_as_MySQLdb()  # 使得SQLAlchemy支持python3版本

app = Flask(__name__)
app._static_folder = "./templates/static"
app.config['SECRET_KEY'] = "why would I tell you my secret key?"
host = '127.0.0.1'
user = 'root'
password = '997968284'


@app.route('/')
def index():
    print("index")
    # sess=request.cookies.get('session')
    # print(sess)
    # if sess is None:
    #     print("none")
    return render_template("index.html")
    # return render_template("index.html")


@app.route('/doRegister', methods=['POST'])
def doRegister():  # 1..
    '''注册'''
    print("register...")
    # 获取请求数据，并将json字符串解析为json对象
    requestData = json.loads(request.get_data(as_text=True))
    username = requestData.get('username')
    phonenumber = requestData.get('phonenumber')
    email = requestData.get('email')
    password1 = requestData.get("password1")
    password2 = requestData.get("password2")
    userType = requestData.get("userType")

    if isExist("user_name", username) is True:  # 判断用户名是否已经存在
        return responseData('101', None, '用户名已存在', username)
    if isUsernameLegal(username) is False:  # 判断用户名是否合法
        return responseData('102', None, '用户名不合法', '')
    if password1 != password2:
        return responseData('103', None, '两次输入的密码不一致', '')

    # 用户id，由系统生成，15位
    userid = str(userType) + time.strftime("%Y%m%d", time.localtime()) + str(random.randint(100000, 1000000))
    while isExist("user_id", userid):  # 判断userid是否已经存在，存在则重新生成
        userid = userType + time.strftime("%Y%m%d", time.localtime()) + str(random.randint(100000, 1000000))

    # 注册数据存储数据表中
    flag = insert_to_user_register(userid, username, phonenumber, email, password1)
    # 返回注册结果
    if flag:
        return responseData('100', None, '注册成功', username)
    else:
        return responseData('104', None, '注册失败', username)


@app.route('/doLogin', methods=['POST'])
def doLogin():  # 2..
    '''登录'''
    print("login...")
    # 获取请求数据，并将json字符串解析为json对象
    requestData = json.loads(request.get_data(as_text=True))
    username = requestData.get("username")  # 获取用户名
    password = requestData.get("password")  # 获取密码
    # 返回登录结果和数据
    if username in session:
        return responseData('201', session.get(username), '已登录', username)
    if isExist("user_name", username) is True:  # 用户名存在
        password_db = query_by_username(username).get("password")
        if password_db != password:  # 密码不正确
            return responseData('202', None, '密码错误', username)
        updateSession(username)  # 更新session
        res = responseData('200', session.get(username), '登录成功', username)
        res.set_cookie('username', username)  # 设置cookie
        return res
    else:
        return responseData('203', None, '用户不存在', username)


def updateSession(username):
    '''更新session'''
    user_info = query_user_information(username)  # 用户信息，key-value类型
    user_info["user_name"] = username
    user_info["sign_up_date"] = user_info["sign_up_date"].strftime('%Y%m%d')  # datetime类型字符串化
    if user_info['user_id'][0] == '1' and user_info["date_of_birth"] != None:  # 个人
        user_info["date_of_birth"] = user_info["date_of_birth"].strftime('%Y%m%d')
    elif user_info['user_id'][0] == '0' and user_info["establish_date"] != None:  # 组织
        user_info["establish_date"] = user_info["establish_date"].strftime('%Y%m%d')
    session[username] = user_info  # 设置session


@app.route('/doLogout', methods=['GET'])
def doLogout():  # 3..
    '''退出'''
    print("logout...")
    # 获取请求数据，并将json字符串解析为json对象
    username = request.cookies.get('username')
    sess = request.cookies.get('session')
    print(username, sess)
    # username = requestData.get("username")  # 获取用户名
    # password = requestData.get("password")  # 获取密码
    # print(session.get(username))
    # print(username)
    print(session)
    # if username in session:
    #     print("yes")
    # else:
    #     print('no')
    #     print(session[username])
    session.pop(username, None)  # 删除session
    # print(session)
    # if username in session:
    #     print("yes")
    # else:
    #     print('no')
    res = make_response(json.dumps(Result(400, None, "退出成功").__dict__))
    res.headers["Content-Type"] = "application/json,charset=utf-8"
    res.delete_cookie('username')  # 设置cookie
    return res


@app.route('/doDeleteUser', methods=['POST'])
def doDeleteUser():  # 4..
    '''删除用户'''
    print("deleteUser...")
    username = request.cookies.get('username')
    requestData = json.loads(request.get_data(as_text=True))
    password = requestData.get("password")  # 获取密码
    print(username, password)

    if username in session:  # 用户已登录
        password_db = query_by_username(username).get("password")
    else:
        res = make_response(json.dumps(Result(301, None, "请重新登录").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 尚未登录".format(username))
        return res
    if password == password_db:
        flag = deleteUserFromDB(username)
        if flag:
            res = make_response(json.dumps(Result(300, None, "注销成功").__dict__))
            res.headers["Content-Type"] = "application/json,charset=utf-8"
            session.pop(username, None)  # 删除session
            print("{} 注销成功".format(username))
            return res
        else:
            res = make_response(json.dumps(Result(302, None, "注销失败").__dict__))
            res.headers["Content-Type"] = "application/json,charset=utf-8"
            print("{} 注销失败".format(username))
            return res
    else:
        res = make_response(json.dumps(Result(303, None, "密码不正确").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 密码不正确".format(username))
        return res


@app.route('/doIsLogin', methods=['GET'])
def doIsLogin():  # 5..
    '''判断用户是否登录'''
    print("isLogin...")
    username = request.cookies.get('username')
    sessionid = request.cookies.get('session')

    if sessionid is None or username is None:
        res = make_response(json.dumps(Result(501, None, "用户未登录").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 未登录".format("用户"))
        return res
    else:
        res = make_response(json.dumps(Result(500, session.get(username), "用户已登录").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 已登录".format(username))
        return res


@app.route('/doModifyPW', methods=['POST'])
def doModifyPW():  # 6..
    '''修改密码'''
    print("modifyPW...")
    username = request.cookies.get('username')
    requestData = json.loads(request.get_data(as_text=True))
    password1 = requestData.get("password1")  # 获取旧密码
    password2 = requestData.get("password1")  # 获取新密码
    print(username, password1, password2)

    if username in session:  # 用户已登录
        password_db = query_by_username(username).get("password")
    else:
        res = make_response(json.dumps(Result(601, None, "请重新登录").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 尚未登录".format(username))
        return res

    if password1 != password_db:
        res = make_response(json.dumps(Result(602, None, "旧密码错输").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 旧密码错误".format(username))
    elif password2 == password_db:
        res = make_response(json.dumps(Result(602, None, "新旧密码相同").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 新旧密码相同".format(username))
    else:
        res = make_response(json.dumps(Result(600, None, "修改成功").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("{} 修改成功".format(username))
        session.pop(username, None)  # 删除session
    return res


@app.route('/doUploadFile', methods=['POST'])
def doUploadFile():  # 7..
    '''上传图片'''
    print("uploadFile...")
    username = request.cookies.get('username')
    img = request.files.to_dict().get('portrait_image')  # 获取上传的文件
    imgtype = '.' + img.content_type.split('/')[1]
    if username not in session:  # 用户未登录
        return responseData('701', None, '尚未登录', username)
    else:
        user_id = query_by_username(username).get("user_id", None)
        if user_id is None:
            return responseData('702', None, '上传失败', username)
        imagename = r"static/portrait_image/" + user_id + imgtype  # 使用原生字符串
        tables = ["organization_user_information", "personal_user_information", "admin_user_information"]
        flag = modifyInformation(tables[int(user_id[0])], "user_id", user_id, "head_portrait", imagename)
        # 保存图片到服务器
        print(session[username].get('head_portrait'))
        old_path = session[username].get('head_portrait')
        if old_path!=None and os.path.exists("templates/" + old_path):  # 删除旧头像
            os.remove("templates/" + old_path)
        img.save("templates/" + imagename)
        if flag:
            updateSession(username)  # 更新session
            return responseData('700', None, '上传成功', username)
        else:
            return responseData('703', None, '上传成功', username)


@app.route('/doModifyInfo', methods=['POST'])
def doModifyInfo():  # 8..
    '''修改用户信息'''
    username = request.cookies.get('username')
    newInfo = request.get_json()  # 获取修改后的信息
    attribute = list(newInfo.keys())[0]  # key
    attribute_value = list(newInfo.values())[0]  # value

    user_id = query_by_username(username).get("user_id", None)
    if user_id is None:
        return responseData('801', None, '用户错误', username)

    attributes = ["user_id", "sign_up_date"]
    if attribute in attributes:
        return responseData('802', None, '{} 不允许修改'.format(attribute), username)

    tables = ["organization_user_information", "personal_user_information", "admin_user_information"]
    flag = modifyInformation(tables[int(user_id[0])], "user_id", user_id, attribute, attribute_value)
    if flag:
        updateSession(username)  # 更新session
        return responseData('800', None, '修改 {} 成功'.format(attribute), username)
    else:
        return responseData('802', None, '修改 {} 失败'.format(attribute), username)


@app.route('/getRotationChart', methods=['GET'])
def getRotationChart():  # 9..
    '''获取轮播图的图片'''
    db = Database(table='rotation_chart_images', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.Cursor)
    images = []
    for e in list(db.query_all_records()):
        images.append(e[0])
    if images == []:
        res = make_response(json.dumps(Result(901, None, "轮播图获取失败").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("轮播图获取失败".format())
        return res

    res = make_response(json.dumps(Result(900, images, "轮播图获取成功").__dict__))
    res.headers["Content-Type"] = "application/json,charset=utf-8"
    print("轮播图获取成功".format())
    return res


@app.route('/getFunds', methods=['GET'])
def getFunds():  # 10..
    '''获取爱心基金'''
    db = Database(table='love_fund', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    funds = db.query_all_records('fund_id,fund_name')
    if funds == []:
        res = make_response(json.dumps(Result(1001, None, "爱心基金获取失败").__dict__))
        res.headers["Content-Type"] = "application/json,charset=utf-8"
        print("爱心基金获取失败".format())
        return res
    res = make_response(json.dumps(Result(1000, funds, "爱心基金获取成功").__dict__))
    res.headers["Content-Type"] = "application/json,charset=utf-8"
    print("爱心基金取成功".format())
    return res


@app.route('/doDonationPost', methods=['POST'])
def doDonationPost():  # 11..
    '''捐款申请提交'''
    print('donationPost...')
    username = request.cookies.get('username')
    requestData = request.get_json()  # 获取修改后的信息
    if username not in session:  # 用户未登录
        return responseData('1101', None, '尚未登录', username)
    else:
        user_id = query_by_username(username).get("user_id", None)
        if user_id is None:
            return responseData('1102', None, '提交失败', username)
        db = Database(table='seek_post', host='127.0.0.1', user='root', password='997968284',
                      database='flaskdb',
                      cursorclass=pymysql.cursors.DictCursor)
        fund_id = requestData.get('fund_id')
        amount_of_money = requestData.get('amount_of_money')
        comment = requestData.get('comment')
        print(fund_id, amount_of_money, comment)

        # fund_balance = db.query_a_records('fund_id', fund_id, attributes='fund_balance').get('fund_balance', 0)
        # db.modifyInformation('fund_id', fund_id, 'fund_balance', fund_balance+amount_of_money)
        # 需要修改 20220311
        return responseData('1100', None, '提交成功', username)


@app.route('/doSeekHelpPost', methods=['POST'])
def doSeekHelpPost():  # 12..
    '''寻求帮助帖'''
    print('seekHelpPost...')
    username = request.cookies.get('username')
    if username not in session:  # 用户未登录
        return responseData('1201', None, '尚未登录', username)
    else:
        user_id = query_by_username(username).get("user_id", None)
        if user_id is None:
            return responseData('1202', None, '提交失败', username)
        # 获取request数据
        requestData = request.get_json()  # 获取修改后的信息
        post_id = requestData.get('post_type', '000') + time.strftime("%Y%m%d", time.localtime()) + str(
            random.randint(1000, 10000))
        publisher_id = user_id
        theme = requestData.get('theme')
        content = requestData.get('content')
        effective_date = max(requestData.get('effective_date'), datetime.datetime.now().strftime("%Y-%m-%d"))
        # 插入数据库
        flag = insert_to_post('seek_post', post_id, publisher_id, theme, content, effective_date)
        if flag:
            return responseData('1200', None, '提交成功', username)
        else:
            return responseData('1203', None, '提交失败', username)


@app.route('/doProvideHelpPost', methods=['POST'])
def doProvideHelpPost():  # 13..
    '''寻求医疗帮助帖'''
    print('provideHelpPost...')
    username = request.cookies.get('username')
    if username not in session:  # 用户未登录
        return responseData('1301', None, '尚未登录', username)
    else:
        user_id = query_by_username(username).get("user_id", None)
        if user_id is None:
            return responseData('1302', None, '提交失败', username)
        # 获取request数据
        requestData = request.get_json()  # 获取修改后的信息
        post_id = requestData.get('post_type', '000') + time.strftime("%Y%m%d", time.localtime()) + str(
            random.randint(1000, 10000))
        publisher_id = user_id
        theme = requestData.get('theme')
        content = requestData.get('content')
        effective_date = max(requestData.get('effective_date'), datetime.datetime.now().strftime("%Y-%m-%d"))
        # 插入数据库
        flag = insert_to_post('help_post', post_id, publisher_id, theme, content, effective_date)
        if flag:
            return responseData('1300', None, '提交成功', username)
        else:
            return responseData('1303', None, '提交失败', username)


@app.route('/getHelpInfomation', methods=['GET'])
def getHelpInfomation():  # 14.
    '''获取互助记录'''
    db = Database(table='mutual_help_info', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    helpInfos = db.query_all_records()
    if helpInfos == []:
        return responseData('1401', None, '互助记录获取失败', '')
    for helpInfo in helpInfos:
        if helpInfo.get('help_date', None) is not None:
            helpInfo["help_date"] = helpInfo["help_date"].strftime('%Y%m%d')
    return responseData('1400', helpInfos, '互助记录获取成功', '')


@app.route('/getLoveOrganization', methods=['GET'])
def getLoveOrganization():  # 15.
    '''获取爱心公益组织'''
    db = Database(table='organization_user_information', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    loveOrgs = db.query_all_records('user_id,short_name,head_portrait')
    if loveOrgs == []:
        return responseData('1501', None, '公益组织获取失败', '')
    return responseData('1500', loveOrgs, '公益组织获取成功', '')


@app.route('/getBillboard', methods=['GET'])
def getBillboard():  # 16.
    '''获取爱心公益组织'''
    print("getBillboard...")
    db = Database(table='publicity_display', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    billboards = db.query_all_records()
    if billboards == []:
        return responseData('1601', None, '宣传展示栏获取失败', '')
    return responseData('1600', billboards, '宣传展示栏获取成功', '')


@app.route('/doModifyOrgImage', methods=['POST'])
def doModifyOrgImage():  # 17.
    '''修改宣传展示栏的背景图片'''
    print('modifyOrgImage...')
    username = request.cookies.get('username')
    if username not in session:  # 用户未登录
        return responseData('1701', None, '请登录后操作', username)
    else:
        user_id = query_by_username(username).get("user_id", None)
        if user_id is None:
            return responseData('1702', None, '背景图片上传失败', username)
        img = request.files.to_dict().get('bg_image')

        imgname = img.filename.split(':')[1]
        imgtype = '.' + img.content_type.split('/')[1]
        imagename = r"static/bg_image/" + imgname + imgtype  # 使用原生字符串
        flag = modifyInformation('publicity_display', "owner_id", user_id, "publicity_pictures", imagename)
        # 保存图片到服务器
        img.save("templates/" + imagename)
        if flag:
            return responseData('1700', None, '背景图片上传成功', username)
        else:
            return responseData('1703', None, '背景图片上传失败', username)


@app.route('/doModifyOrg', methods=['POST'])
def doModifyOrg():  # 18.
    '''修改宣传展示栏'''
    print('modifyOrg...')
    username = request.cookies.get('username')
    newInfo = request.get_json()  # 获取修改后的信息
    publicity_title = newInfo.get('publicity_title', None)
    publicity_content = newInfo.get('publicity_content', None)

    user_id = query_by_username(username).get("user_id", None)
    if user_id is None:
        return responseData('1801', None, '用户错误', username)
    flag1, flag2 = True, True
    if publicity_title != '':
        flag1 = modifyInformation('publicity_display', "owner_id", user_id, 'publicity_title', publicity_title)
    if publicity_content != '':
        flag2 = modifyInformation('publicity_display', "owner_id", user_id, 'publicity_content', publicity_content)
    if flag1 and flag2:
        return responseData('1800', None, '更新宣传展示栏成功', username)
    else:
        return responseData('1802', None, '更新宣传展示栏失败', username)


@app.route('/getOrganizationInfo/<string:user_id>', methods=['GET'])
def getOrganizationInfo(user_id):  # 19.
    '''获取一个组织的信息'''
    username = request.cookies.get('username')
    db = Database(table='organization_user_information', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    orgInfo = db.query_a_records('user_id', user_id)

    if orgInfo == {}:
        return responseData('1901', None, '获取组织详细信息失败', username)
    if orgInfo.get('sign_up_date', None) is not None:
        orgInfo["sign_up_date"] = orgInfo["sign_up_date"].strftime('%Y%m%d')
    if orgInfo.get('establish_date', None) is not None:
        orgInfo["establish_date"] = orgInfo["establish_date"].strftime('%Y%m%d')

    return responseData('1900', orgInfo, '获取组织详细信息成功', username)


@app.route('/getOnePost/<string:post_id>', methods=['GET'])
def getOnePost(post_id):  # 20.
    '''获取一个帖子'''
    username = request.cookies.get('username')
    tables = {'S': 'seek_post', 'P': 'help_post'}
    db = Database(table=tables[post_id[0]], host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    post = db.query_a_records('post_id', post_id)

    if post == {}:
        return responseData('2001', None, '获取帖子失败', username)
    if post.get('publish_date', None) is not None:
        post["publish_date"] = post["publish_date"].strftime('%Y%m%d %H:%M')
    if post.get('effective_date', None) is not None:
        post["effective_date"] = post["effective_date"].strftime('%Y%m%d')
    return responseData('2000', post, '获取帖子成功', username)


@app.route('/getAllNotice', methods=['GET'])
def getAllNotice():  # 21.
    '''获取公告'''
    db = Database(table='notice', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    notices = db.query_all_records()
    if notices == []:
        return responseData('2101', None, '公告获取失败', '')
    for notice in notices:
        notice["publish_date"] = notice["publish_date"].strftime('%Y%m%d')
    return responseData('2100', notices, '公告获取成功', '')


@app.route('/doPublishNotice', methods=['POST'])
def doPublishNotice():  # 21.
    '''发布公告'''
    print('publishNotice...')
    username = request.cookies.get('username')
    if username not in session:  # 用户未登录
        return responseData('2101', None, '请登录后操作', username)
    user_id = query_by_username(username).get("user_id", None)
    if user_id is None:
        return responseData('2102', None, '公告发布失败', username)
    noticeInfo = request.get_json()  # 获取修改后的信息
    publish_date = noticeInfo.get('publish_date', None)
    content = noticeInfo.get('content', None)
    notice_id = time.strftime("%Y%m%d%H%M", time.localtime()) + str(random.randint(100, 1000))
    if publish_date is '':
        publish_date = time.strftime("%Y%m%d", time.localtime())
    flag = insert_to_notice(notice_id, user_id, publish_date, content)
    if flag:
        return responseData('2100', None, '公告发布成功', username)
    else:
        return responseData('2103', None, '公告发布失败', username)


@app.route('/doDeletePost', methods=['POST'])
def doDeletePost():  # 22.
    '''删除帖子'''
    print('deletePost...')
    username = request.cookies.get('username')
    if username not in session:  # 用户未登录
        return responseData('2201', None, '请登录后操作', username)
    user_id = query_by_username(username).get("user_id", None)
    if user_id is None:
        return responseData('2202', None, '删帖失败', username)
    if user_id[0] is not '2':
        return responseData('2203', None, '非管理员不许删帖', username)
    post_id = request.get_json().get('post_id', None)  # 获取修改后的信息
    if post_id is '':
        return responseData('2204', None, '请输入帖子id', username)
    elif post_id[0] is 'S':
        table = 'seek_post'
    elif post_id[0] is 'P':
        table = 'help_post'
    else:
        return responseData('2205', None, '帖子id不正确', username)
    flag = delete_from_post(table, post_id)
    if flag:
        return responseData('2200', None, '删帖成功', username)
    else:
        return responseData('2206', None, '删帖失败', username)


@app.route('/getPost/<string:type>', methods=['GET'])
def getPost(type):  # 23.
    '''获取一个帖子'''
    print('allPost...')
    username = request.cookies.get('username')
    db1 = Database('seek_post', host='127.0.0.1', user='root', password='997968284',
                   database='flaskdb',
                   cursorclass=pymysql.cursors.DictCursor)
    posts1 = db1.query_all_records('post_id,theme,publish_date,checker_id,check_result,finished')
    db2 = Database('help_post', host='127.0.0.1', user='root', password='997968284',
                   database='flaskdb',
                   cursorclass=pymysql.cursors.DictCursor)
    posts2 = db2.query_all_records('post_id,theme,publish_date,checker_id,check_result,finished')

    all_posts = list(posts1) + list(posts2)
    if all_posts is []:
        return responseData('2301', None, '未获取到帖子', username)
    posts = []
    if type == 'part':  # 获取待审核的帖子
        for post in all_posts:
            if post['checker_id'] == '000000000000000':  # 未审核
                posts.append(post)
    elif type == 'all':  # 获取审核通过的所有帖子
        for post in all_posts:
            if post['check_result'] == 'Y' and post['finished'] != 'Y':  # 审核通过,且未结束
                posts.append(post)
    else:
        return responseData('2302', posts, '获取帖子失败', username)
    for post in posts:
        if post.get('publish_date', None) is not None:
            post["publish_date"] = post["publish_date"].strftime('%Y%m%d %H:%M')
    return responseData('2300', posts, '获取帖子成功', username)


@app.route('/doVerifyPost', methods=['POST'])
def doVerifyPost():  # 24.
    '''修改帖子的审核结果'''
    print('verifyPost...')
    username = request.cookies.get('username')
    if username not in session:  # 用户未登录
        return responseData('2401', None, '请登录后操作', username)
    user_id = query_by_username(username).get("user_id", None)
    if user_id is None:
        return responseData('2402', None, '审核操作失败', username)
    if user_id[0] is not '2':
        return responseData('2203', None, '非管理员无审核权限', username)
    check = request.get_json()  # 获取审核信息
    post_id = check.get('post_id', None)
    check_result = check.get('check_result', None)
    if post_id == '' or check_result == '':
        return responseData('2404', None, '审核操作失败', username)
    elif post_id[0] is 'S':
        table = 'seek_post'
    elif post_id[0] is 'P':
        table = 'help_post'
    else:
        return responseData('2405', None, '审核操作失败', username)
    flag1 = modifyInformation(table, 'post_id', post_id, 'checker_id', user_id)
    flag2 = modifyInformation(table, 'post_id', post_id, 'check_result', check_result)
    if flag1 and flag2:
        return responseData('2400', None, '审核操作成功', username)
    else:
        return responseData('2406', None, '审核操作失败', username)


@app.route('/getIndividualInfo/<string:user_id>', methods=['GET'])
def getIndividualInfo(user_id):  # 25.
    '''获取一个个人的信息'''
    print('individualInfo...')
    username = request.cookies.get('username')
    db = Database(table='personal_user_information', host='127.0.0.1', user='root', password='997968284',
                  database='flaskdb',
                  cursorclass=pymysql.cursors.DictCursor)
    indInfo = db.query_a_records('user_id', user_id)
    if indInfo == {}:
        return responseData('2501', None, '获取个人详细信息失败', username)
    if indInfo.get('sign_up_date', None) is not None:
        indInfo["sign_up_date"] = indInfo["sign_up_date"].strftime('%Y%m%d')
    if indInfo.get('date_of_birth', None) is not None:
        indInfo["date_of_birth"] = indInfo["date_of_birth"].strftime('%Y%m%d')
    return responseData('2500', indInfo, '获取个人详细信息成功', username)


@app.route('/doMakeHelp', methods=['POST'])
def doMakeHelp():  # 26.
    '''提供帮助/接受帮助'''
    print('makeHelp...')
    username = request.cookies.get('username')
    if username not in session:  # 用户未登录
        return responseData('2601', None, '请登录后操作', username)
    user_id = query_by_username(username).get("user_id", None)
    if user_id is None:
        return responseData('2602', None, '互助失败', username)
    info = request.get_json()  # 获取修改后的信息
    seek_id = info.get('seek_id', None)
    post_id = info.get('post_id', None)
    mutual_help_id = post_id[0:3] + time.strftime("%Y%m%d", time.localtime()) + str(random.randint(1000, 10000))
    if seek_id == '' or post_id == '':
        return responseData('2603', None, '互助失败', username)
    elif post_id[0] is 'S':
        table = 'seek_post'
    elif post_id[0] is 'P':
        table = 'help_post'
    title = 'title'
    content = 'content'
    flag1 = insert_to_mutual_help_info(mutual_help_id, user_id, seek_id, post_id, title, content)
    flag2 = modifyInformation(table, 'post_id', post_id, 'finished', 'Y')  # 已结束
    if flag1 and flag2:
        return responseData('2600', None, '互助成功', username)
    else:
        return responseData('2604', None, '互助失败', username)


def responseData(code, data, description, username=''):
    '''构造返回数据包'''
    res = make_response(json.dumps(Result(code, data, description).__dict__))
    res.headers["Content-Type"] = "application/json,charset=utf-8"
    print("Code {}: {} {}".format(code, username, description))
    return res


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
    # server = pywsgi.WSGIServer(('0.0.0.0', 8080), app)
    # server.serve_forever()
